package com.systop.scos.news.webapp;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;

import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.dao.support.Page;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.DefaultCrudAction;
import com.systop.scos.news.model.NewsComment;
import com.systop.scos.news.service.NewsCommentManager;
import com.systop.scos.news.service.NewsManager;

/**
 * 新闻评论Action
 * 
 * @author ShangHua
 * 
 */
@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class NewsCommentAction extends
		DefaultCrudAction<NewsComment, NewsCommentManager> {

	// 评论对应的新闻ID
	private Integer newsId;

	@Autowired
	private NewsManager newsManager;

	/**
	 * 重写父类的index方法，实现分页检索年得分信息
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String index() {
		String hql = "from NewsComment nc where nc.news.id = ?  order by nc.createTime desc";
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		getManager().pageQuery(page, hql.toString(), newsId);
		items = page.getData();
		restorePageData(page);
		return INDEX;
	}

	/**
	 * 保存新闻评论信息
	 */
	public String commentSave() {
		Assert.notNull(getLoginUser());
		// 有特殊原因,因为评论的提交页面在news的view页面，所以model.content无法区分.
		String commentContent = getRequest().getParameter("commentContent");
		getModel().setContent(commentContent);
		getModel().setCreateTime(new Date());
		getModel().setCommenter(getLoginUser());
		getModel().setNews(newsManager.get(newsId));
		getManager().save(getModel());

		return SUCCESS;
	}

	/**
	 * @return 用户登录信息
	 */
	private User getLoginUser() {
		User user = UserUtil.getPrincipal(getRequest());
		return user;
	}

	public Integer getNewsId() {
		return newsId;
	}

	public void setNewsId(Integer newsId) {
		this.newsId = newsId;
	}
}
